<!--
 * @Author: weidewei
 * @Date: 2025-11-04 10:31:35
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-04 11:17:56
 * @Description: 
 * @FilePath: \2025-front-face\review-knowledge\20251104\复习节流函数.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">按钮疯狂点击</button>
    <script>
      // 时间戳版
      function throttleTimeStamp(fun, wait = 500) {
        let lastTime = 0;
        return function (...args) {
          let nowTime = Date.now();
          if (nowTime - lastTime > wait) {
            fun.apply(this, args);
            lastTime = nowTime;
          }
        };
      }

      // 定时器版本
      function throttleSettimeout(fun, wait = 500) {
        let timeout;
        return function (...args) {
          if (timeout) return;
          timeout =  setTimeout(() => {
            fun.apply(this, args);
            timeout = null;
          }, wait);
          // 不能在这里设置timeout为null,否则会立即执行
        };
      }

      const btn = document.querySelector("#btn");
      btn.addEventListener(
        "click",
        throttleSettimeout(function () {
          console.log("输出值", this.value);
        }, 1500)
      );
    </script>
  </body>
</html>
